<template lang="html">
  <input
    type="text"
    v-model="inputValue"
    @blur="inputBlur"
  />
</template>

<script>
import { mapActions, mapState } from 'vuex'
import * as $helpers from '../utils/helpers'
import * as $types from '../vuex/mutation-types'

export default {
  props: ['transformer', 'index'],
  computed: {
    inputValue: {
      get() {
        const path = this.$attrs.name
        const { state } = this.$store
        return $helpers.getValueByPath(state, path)
      },
      set(value) {
        const path = this.$attrs.name
        const { transformer } = this
        const { state } = this.$store
        const oldValue = $helpers.getValueByPath(state, path)
        if ('function' === typeof transformer) {
          value = transformer(value, oldValue)
        }
        this.$store.commit('updateInputValue', { value, path })
        if (value !== oldValue) {
          this.$emit('input-value-changed', value)
        }
      }
    }
  },
  methods: {
    inputBlur() {
      const { readonly } = this.$attrs
      if (readonly) {
        return
      }
      this.$emit('input-blur', this.index)
    }
  }
}
</script>

<style lang="css">
</style>
